package com.xiaoma.juc.semaphore;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemaphoreRunable implements Runnable{
    private int num;
    private Semaphore semaphore;
    
    public SemaphoreRunable(int num,Semaphore semaphore){
        this.num = num;
        this.semaphore = semaphore;
    }
    
    @Override
    public void run() {
        try {
            semaphore.acquire();
            // 模拟线程的执行操作
            System.out.println("工人"+this.num+"占用一个机器在生产...");
            Thread.sleep(Math.abs(new Random().nextInt()%10000));
            System.out.println("工人"+this.num+"释放出机器");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    public static void main(String[] args) {
        int N = 8;  //工人数
        Semaphore semaphore = new Semaphore(5); //机器数目
        for(int i=0;i<N;i++) {
            new Thread(new SemaphoreRunable(i, semaphore)).start();
        }
    }
}

